/**
 * Created by muyonghui on 17/2/23.
 */
const url = require('url');
const cheerio = require('cheerio');
const request = require('request');
const iconv = require('iconv-lite');
const BufferHelper = require('bufferhelper');
const fs = require('fs');
const querystring = require('querystring');
const _async = require('async');
const jRequest = request.defaults({jar: true});
const tesseract = require('node-tesseract');
const gm = require('gm');


function initPostData(userName, password, verifyCode, viewState) {
    var rawPost = {
        __VIEWSTATE: viewState,
        txtUserName: userName,
        TextBox2: password,
        txtSecretCode: verifyCode,
        Button1: "",
        lbLanguage: "",
        hidPdrs: "",
        hidsc: ""
    };
    var postData = querystring.stringify(rawPost);
    postData += "&RadioButtonList1=%D1%A7%C9%FA";

    return postData;
}

function resolveGB2312Html(buffer) {
    var bufferHelper = new BufferHelper();
    bufferHelper.concat(buffer);
    return iconv.decode(bufferHelper.toBuffer(), 'gb2312').toString();
}

const entryUrl = "http://jwgl1.hznu.edu.cn/";

codeTest();
function codeTest() {

    jRequest({
        url: entryUrl + 'default2.aspx'
    }, function (err, res, body) {//首页请求
        if (err) {
            return console.error(err)
        }
        var $ = cheerio.load(body);
        var eventTarget = $('input[name=__EVENTTARGET]').attr('value');
        var eventArgument = $('input[name=__EVENTARGUMENT]').attr('value');
        var viewState = $('input[name=__VIEWSTATE]').attr('value');

        var cookie = res.client._httpMessage.path.toString();
        cookie = cookie.match(/\([a-z,A-Z,0-9]*\)/);
        if (cookie != null) {
            cookie = cookie[0] + '/';
        } else {
            cookie = ""
        }
        var loginUrl = url.resolve(entryUrl, cookie + 'default2.aspx');
        loginInfo = {
            cookie: cookie,
            eventTarget: eventTarget,
            eventArgument: eventArgument,
            viewState: viewState,
            loginUrl: loginUrl,
            entryUrl: entryUrl,
            txtusername: "txtUserName",
            txtpassword: "TextBox2",
            txtsecretcode: "txtSecretCode"
        }


        var codeBuffer = new BufferHelper();

        jRequest.get({
                url: entryUrl + cookie + 'CheckCode.aspx',
                //Referer:entryUrl,
                followAllRedirects: true
            }
        )//获取验证码
            .on('error', function (err) {
                console.log(err);
            })
            .on('data', function (chunck) {
                codeBuffer.concat(chunck);
            })
            .on('end', function () {
                var con = codeBuffer.toBuffer();
                fs.writeFileSync('code.jpg', con);
                // console.log(con);
                // ress.send(con);
                processImg('code.jpg', 'code_1.jpg')
                    .then(recognizer)
                    .then(text => {
                        console.log(`识别结果:${text}`);
                    })
                    .catch((err)=> {
                        console.error(`识别失败:${err}`);
                    });

            });
    });

}


/**
 * 处理图片为阈值图片
 * @param imgPath
 * @param newPath
 * @param [thresholdVal=55] 默认阈值
 * @returns {Promise}
 */
function processImg (imgPath, newPath, thresholdVal) {
    return new Promise((resolve, reject) => {
            gm(imgPath)
            .threshold(thresholdVal || 55)
            .write(newPath, (err)=> {
            if (err) return reject(err);

    resolve(newPath);
});
});
}

/**
 * 识别图片
 * @param imgPath
 * @param options tesseract options
 * @returns {Promise}
 */
function recognizer (imgPath, options) {
    options = Object.assign({psm: 7}, options);

    return new Promise((resolve, reject) => {
            tesseract
            .process(imgPath, options, (err, text) => {
            if (err) return reject(err);
    resolve(text.replace(/[\r\n\s]/gm, ''));
});
});
}

function xx() {
    jRequest.post({
        url: "http://jwgl1.hznu.edu.cn/default2.aspx",
        form: postData,
        encoding: null,
        headers: {
            Host:"jwgl1.hznu.edu.cn",
            Origin:"http://jwgl1.hznu.edu.cn",
            Referer: "http://jwgl1.hznu.edu.cn/default2.aspx",
            Cookie: "ASP.NET_SessionId=cjrdhs45gimgj2452nrqwgfn; insert_cookie=67313298"
        }
    }, function (err, res, body) {//首页请求
        if (err) {
            return console.error(err)
        }
        var recoded_html = resolveGB2312Html(body);
        var $ = cheerio.load(body);
        console.log(recoded_html);
        var eventTarget = $('input[name=__EVENTTARGET]').attr('value');
        var eventArgument = $('input[name=__EVENTARGUMENT]').attr('value');
        var viewState = $('input[name=__VIEWSTATE]').attr('value');

        var cookie = res.client._httpMessage.path.toString();
        cookie = cookie.match(/\([a-z,A-Z,0-9]*\)/);
        if (cookie != null) {
            cookie = cookie[0] + '/';
        } else {
            cookie = ""
        }



    });
}
